package org.mbds.android.p2p.services;
import org.mbds.*;

import org.mbds.android.sismapp.R;
import org.mbds.android.sismapp.SismappMessage;
import org.mbds.android.sismapp.activity.P2pActivity;
import org.mbds.android.sismapp.activity.SensorDataCollectorActivity;


import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.view.View;
import android.widget.Toast;

//Create a handler that will deal with messages sent back from the P2pservice.
		public class P2pServiceMessageHandler extends Handler{
			NotificationCompat.Builder mBuilder;
			SensorDataCollectorActivity act;
			
			public P2pServiceMessageHandler(
					SensorDataCollectorActivity sensorDataCollectorActivity) {
				act = sensorDataCollectorActivity;
			}
			@Override
			public void handleMessage(Message msg){
				switch(msg.what){
				case P2pService.TYPE_MESSAGE_SENT :
					boolean result = (Boolean)msg.obj; // A message has been or not sent to peers. Don't know yet what to do with this boolean
					break; 
				case P2pService.TYPE_RECEIVED_MESSAGE : // Delegate the received message to the appropriate method
					try {
						SismappMessage.receiveSismappMessage((String)msg.obj);
						Toast.makeText(act.getApplicationContext(), "RECEived", Toast.LENGTH_SHORT).show();
						//setUpNotification((String)msg.obj);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;
				case P2pService.TYPE_CLIENT_REGISTERED :
					try {
						SismappMessage.receiveSismappMessage((String)msg.obj);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;
				default :
					super.handleMessage(msg);
					break;
				}
			}
			
			public void setUpNotification(String message){
				mBuilder = new NotificationCompat.Builder(act)
				.setSmallIcon(R.drawable.ic_launcher)
				.setContentTitle("Notification")
				.setContentText(message);
				mBuilder.setVibrate(new long[]{2000, 3000});
				Intent resultIntent = new Intent(act.getApplicationContext(), SensorDataCollectorActivity.class);
				
				TaskStackBuilder stackBuilder = TaskStackBuilder.create(act.getApplicationContext());
				stackBuilder.addParentStack(SensorDataCollectorActivity.class);
				stackBuilder.addNextIntent(resultIntent);
				
				PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); // We can add a bundle here to retreive data
				mBuilder.setContentIntent(resultPendingIntent);
				NotificationManager ntfmng = (NotificationManager)act.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
				ntfmng.notify(8888, mBuilder.build());
			}
		}
